package vip.xiaonuo.issued.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.mapper.VisitorMapper;
import vip.xiaonuo.facedoor.modular.visitordevice.entity.VisitorDevice;
import vip.xiaonuo.facedoor.modular.visitordevice.mapper.VisitorDeviceMapper;
import vip.xiaonuo.facedoor.iservice.IFaceDoorDtoService;
import vip.xiaonuo.facedoor.iservice.IVisitorDeviceService;
import vip.xiaonuo.facedoor.remote.iservice.adapter.VisitorReqAdapter;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.GetPersonResponse;

import javax.annotation.Resource;

@Service(value = RuleConstant.DW+ RuleConstant.VISITOR_DEVICE)
public class HttpVisitorDeviceServiceImpl implements IVisitorDeviceService {

  @Resource
  private VisitorMapper visitorMapper;

  @Resource
  private VisitorDeviceMapper visitorDeviceMapper;

  @Resource
  private VisitorReqAdapter personService;

  @Resource
  private DeviceBaseService deviceBaseService;

  private void baseCheck(VisitorDevice visitorDevice) {
    if (visitorDevice == null) {
      throw new ServiceException(500, "找不到关联信息！");
    }
    if (visitorDevice.getStatus().equals(MemberDeviceConstant.ADD) || visitorDevice.getStatus().equals(MemberDeviceConstant.UPDATE) || visitorDevice.getStatus().equals(MemberDeviceConstant.DELETE)) {
      throw new ServiceException(500, "非正常状态 不允许操作！");
    }
  }


  @Override
  public void delete(Long id) throws Exception {
    VisitorDevice visitorDevice = visitorDeviceMapper.selectById(id);
    baseCheck(visitorDevice);
    DeviceBase deviceBase = deviceBaseService.getById(visitorDevice.getDeviceId());
    String uri = IFaceDoorDtoService.getBaseParam(deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
    // 新增失败 直接删除人员
    if (visitorDevice.getStatus().equals(MemberDeviceConstant.ADD_FAIL)) {
      visitorDeviceMapper.deleteById(id);
    } else {
      ReturnJson returnJson = personService.deletePerson(visitorDevice, uri);
      // 删除用户成功
      if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
        visitorDeviceMapper.deleteById(visitorDevice.getId());
        long count = visitorDeviceMapper.selectCount(new LambdaQueryWrapper<VisitorDevice>().eq(VisitorDevice::getVisitorId, visitorDevice.getVisitorId()));
        if (count == 0) {
          visitorDeviceMapper.deleteById(visitorDevice.getVisitorId());
        }
      } else {
        throw new ServiceException(500, "删除人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
      }
    }
  }

  @Override
  public void sync(Long id) throws Exception {
    VisitorDevice visitorDevice = this.visitorDeviceMapper.selectById(id);
    baseCheck(visitorDevice);
    if (visitorDevice.getStatus().equals(MemberDeviceConstant.SYNC_SUCCESS)) {
      throw new ServiceException(500, "未发生错误 不允许同步！");
    }
    DeviceBase deviceBase = deviceBaseService.getById(visitorDevice.getDeviceId());
    Visitor visitor = visitorMapper.selectById(visitorDevice.getVisitorId());
    String uri = IFaceDoorDtoService.getBaseParam(deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));

    // 恢复人员状态
    if (visitorDevice.getStatus().equals(MemberDeviceConstant.ADD_FAIL)) {
      // 先查询人员
      GetPersonResponse getPersonResponse = personService.getPerson(uri, visitor);
      // 不存在 新增
      if (StringUtils.isNotBlank(getPersonResponse.getCode()) && "0202".equals(getPersonResponse.getCode())) {
        ReturnJson returnJson = personService.addPerson(uri, visitor);
        if (returnJson.getCode().equals("0000")) {
          visitorDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
          visitorDevice.setFailReason(null);
          visitorDeviceMapper.updateById(visitorDevice);
        } else {
          throw new ServiceException(500, "新增人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
        }
        // 修改
      } else if (StringUtils.isNotBlank(getPersonResponse.getCode()) && "0000".equals(getPersonResponse.getCode())) {
        ReturnJson returnJson = personService.updatePerson(uri, visitor);
        if (returnJson.getCode().equals("0000")) {
          visitorDevice.setFailReason(null);
          visitorDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
          visitorDeviceMapper.updateById(visitorDevice);
        } else {
          throw new ServiceException(500, "人员已经存在设备  修改人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
        }
      } else {
        throw new ServiceException(500, "查询人员发生错误 " + getPersonResponse.getMsg());
      }
    }
    if (visitorDevice.getStatus().equals(MemberDeviceConstant.UPDATE_FAIL)) {

      ReturnJson returnJson = personService.updatePerson(uri, visitor);
      if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
        visitorDevice.setFailReason(null);
        visitorDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        visitorDeviceMapper.updateById(visitorDevice);
      } else if (returnJson.getCode().equals("0202")) {
        ReturnJson addRj = personService.addPerson(uri, visitor);
        // 调用新增接口
        if (addRj.getCode().equals("0000")) {
          visitorDevice.setFailReason(null);
          visitorDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
          visitorDeviceMapper.updateById(visitorDevice);
        } else {
          throw new ServiceException(500, "人员已经存在设备  修改人员发生错误【{" + JSON.toJSONString(addRj) + "}】！");
        }
      } else {
        throw new ServiceException(500, "修改人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
      }
    }
    if (visitorDevice.getStatus().equals(MemberDeviceConstant.DELETE_FAIL)) {
      ReturnJson returnJson = personService.deletePerson(visitorDevice, uri);
      // 删除用户成功
      if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
        visitorDeviceMapper.deleteById(visitorDevice.getId());
        long count = visitorDeviceMapper.selectCount(new LambdaQueryWrapper<VisitorDevice>().eq(VisitorDevice::getVisitorId, visitor.getId()));
        if (count == 0 && ObjectUtil.equal(visitor.getDelFlag(), "1")) {
          visitorMapper.deleteById(visitorDevice.getVisitorId());
        }
      } else {
        throw new ServiceException(500, "删除人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
      }
    }
    visitorDeviceMapper.updateById(visitorDevice);
  }
}
